import logging
import json
import random
import time
from selenium.common.exceptions import WebDriverException
from urllib.parse import urlparse
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from view_geek_info import random_sleep_time
import pyautogui
from time import sleep

# 点击沟通页面
def goutong():
    # 获取当前鼠标位置
    time.sleep(3)  # 等待 3 秒
    cur_x, cur_y = pyautogui.position()
    print(f'当前位置: {cur_x}, {cur_y}')

    time.sleep(3)  # 再等待 3 秒
    pyautogui.moveTo(78, 320, duration=0.5)  # 移动鼠标到指定位置

    # 随机生成点击的持续时间，精确到毫秒
    click_duration = random.uniform(0.5, 2.0)  # 生成 0.5 到 3.0 秒之间的浮点数
    pyautogui.click(78, 320, duration=click_duration)  # 点击，duration 精确到毫秒


# 点击沟通获取全部数据
def quanbu():
    # 获取当前鼠标位置
    sleep(3)
    cur_x, cur_y = pyautogui.position()
    print('当前位置{},{}'.format(cur_x, cur_y))
    sleep(3)
    pyautogui.moveTo(474, 149, duration=0.5)
    # 随机生成点击的持续时间，精确到毫秒
    click_duration = random.uniform(0.5, 2.0)  # 生成 0.5 到 3.0 秒之间的浮点数
    pyautogui.click(474, 149, duration=click_duration)  # 点击，duration 精确到毫秒

def get_boss_filterByLabel(driver):
    captured_urls = []
    # 清空浏览器日志缓冲区
    driver.get_log("performance")
    random_sleep_time()

    # # 点击切换页面
    # goutong()
    refresh_btn = driver.find_element(By.XPATH, '//*[@id="wrap"]/div[1]/div[1]/dl[4]/dt/a')
    # 创建 ActionChains 对象
    actions = ActionChains(driver)
    # 将鼠标移动到目标元素并点击
    actions.move_to_element(refresh_btn).click().perform()
    # 等待页面加载
    random_sleep_time()
    logging.info("切换沟通页面")

    # 点击全部列表获取filterByLabel接口数据
    # quanbu()
    refresh_btns = driver.find_element(By.XPATH, '//*[@id="container"]/div[1]/div/div[2]/div[1]/div/div/div/div[1]')
    # 创建 ActionChains 对象
    actions = ActionChains(driver)
    # 将鼠标移动到目标元素并点击
    actions.move_to_element(refresh_btns).click().perform()
    random_sleep_time()

    # 每次页面加载后，启用 Network 并设置缓冲区
    driver.execute_cdp_cmd("Network.enable", {
        "maxTotalBufferSize": 10000000,
        "maxResourceBufferSize": 5000000
    })

    # 等待一段时间，确保页面加载并发起请求
    random_sleep_time()

    # 获取浏览器的性能日志
    logs = driver.get_log("performance")

    # 遍历日志，捕获相关网络请求和响应
    for item in logs:
        log = json.loads(item["message"])["message"]

        if log["method"] == 'Network.responseReceived':
            # 获取响应的URL
            urls = log['params']['response']['url']
            captured_urls.append(urls)

            # 定义目标 URL 的路径部分
            target_url_pattern = "https://www.zhipin.com/wapi/zprelation/friend/filterByLabel"

            try:
                # 逐个处理 captured_urls 中的每个 URL
                for captured_url in captured_urls:
                    # 解析 URL
                    parsed_url = urlparse(captured_url)
                    url_path = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"

                    # 检查 URL 路径是否匹配目标 URL
                    if url_path == target_url_pattern:
                        # print("是目标 URL 响应")
                        break
            except Exception as e:
                print(f"发生错误: {e}")

            # 使用检查 URL 是否包含目标路径部分
            if target_url_pattern not in urls:
                continue  # 如果匹配目标 URL，继续处理（或执行其他逻辑）

            # 打印请求的 URL
            print('请求 URL:', urls)
            # 获取请求的ID
            request_id = log['params']['requestId']

            # 尝试获取请求的POST数据
            try:
                request_data = driver.execute_cdp_cmd('Network.getRequestPostData', {'requestId': request_id})
                print('请求数据:', request_data)
            except WebDriverException:  # 没有后台数据获取时会有异常
                request_data = None

            # 获取响应的主体内容
            try:
                response_body = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': request_id}).get(
                    'body', None)
                print('响应体:', response_body)
            except WebDriverException as e:
                print(f"获取响应失败: {e}")

            # 解析 JSON 数据
            data = json.loads(response_body)

            # 提取 friendId 和 friendSource
            friend_data = []
            for friend in data["zpData"]["result"]:
                if friend["friendId"] >= 2000:
                    friend_info = {
                        "friendId": friend["friendId"],
                        "friendSource": friend["friendSource"]
                    }
                    friend_data.append(friend_info)

                # 将提取的数据写入文件
                with open('data/dynamic_ids_s.txt', 'w') as file:
                    for friend in friend_data:
                        file.write(f"_{friend['friendId']}-{friend['friendSource']}\n")

            print('friendId 和 friendSource 已保存到 dynamic_ids_s.txt')
